﻿using System.Windows.Controls;
using System.Windows.Input;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using FixtureManageSystem.Models;
using System.Collections.Generic;
using System.Windows;
using System;
using MySql.Data.MySqlClient;
using System.Data.SQLite;

namespace FixtureManageSystem.ControlWidget
{
    /// <summary>
    /// SearchCombobox.xaml 的交互逻辑
    /// </summary>
    public partial class SearchCombobox : UserControl
    {
        public SearchCombobox()
        {
            InitializeComponent();
        }

        private void ComboBox_KeyUp(object sender, KeyEventArgs e)
        {
            SqliteHelper sqliteHelper = new SqliteHelper();
            List<string> _employees = new List<string>();
            string personNo = (sender as ComboBox).Text;
            // 创建要执行的sql语句
            string str = "";
            if (personNo == str)
                   return;
            if (Regex.IsMatch(personNo, @"^\d+$")){
                str = $"SELECT * FROM Employee WHERE PersonNo LIKE '{personNo}%'";
            }
            else
            {
                str = $"SELECT * FROM Employee WHERE Name LIKE '{personNo}%'";
            }
            // 2、执行SQL语句并接受结果
            SQLiteDataReader Sdr = sqliteHelper.read(str);

            // 4、读取结果的数据
            while (Sdr.Read())
            { 
                _employees.Add(Sdr["Name"].ToString() + " "+ Sdr["PersonNo"].ToString());
            }
            this.SearchCombobx.ItemsSource = _employees;
            this.SearchCombobx.IsDropDownOpen = true;
        }

        public string PersonNo
        {
            get { return (string)GetValue(PersonNoProperty); }
            set
            {
                SetValue(PersonNoProperty, value);
            }
        }
        public static readonly DependencyProperty PersonNoProperty =
            DependencyProperty.Register("PersonNo", typeof(string), typeof(SearchCombobox));

        private void SearchCombobx_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.SearchCombobx.SelectedValue != null)
            {
                string phrase = this.SearchCombobx.SelectedValue.ToString();
                string[] words = phrase.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (words.Length >= 2)
                {
                    PersonNo = words[words.Length - 1];
                    return;
                }
            }
            else
                PersonNo = "";
        }
    }
}
